<template>
  <div class="app-container visitor-list-documentation-container">

    <div class="data-statistics">
      <StatisticsCard
        :list="visitorDataStatistics"
        :loading="statisticsDataLoading"
      />
    </div>

    <div class="search card">
      <el-form :inline="true" :model="form" class="demo-form-inline">
        <el-form-item label="公司名">
          <el-input v-model="form.company_name" placeholder="公司名" />
        </el-form-item>
        <el-form-item label="来访人员">
          <el-input v-model="form.visitor" placeholder="来访人员" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="form.phone" placeholder="手机号" />
        </el-form-item>
        <el-form-item label="日期查询">
          <el-date-picker
            v-model="form.time"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="selectTime"
          />
        </el-form-item>
        <el-form-item label="对接人">
          <el-select
            v-model="form.docking_id"
            v-el-select-loadmore="loadmore"
            clearable
            filterable
            remote
            placeholder="请选择"
            :remote-method="remoteMethod"
            :loading="remoteMethodLoading"
            @focus="handlePersonUser"
          >
            <el-option v-for="item in options" :key="item.id + item" :label="item.username" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="handleRest">重置</el-button>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="list__content card">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="访客记录" name="1">
          <el-table
            v-loading="loading"
            :data="data"
            style="width: 100%"
            border
            :row-style="handleRowStyle"
          >
            <el-table-column prop="company_name" label="公司名称" />
            <el-table-column prop="visitor" label="来访人员（同行人员）">
              <template v-slot="{ row }">
                {{ `${row.visitor}（${row.fellow}人）` }}
              </template>
            </el-table-column>
            <el-table-column prop="visitor_position" label="访客职位">
              <template v-slot="{ row }">
                {{ row.visitor_position && row.visitor_position !== 'null' ? row.visitor_position : '' }}
              </template>
            </el-table-column>
            <el-table-column prop="phone" label="手机号" />
            <el-table-column prop="docking.username" label="对接人员（部门）">
              <template v-slot="{ row }">
                {{ `${row.docking.username}（${row.department.name}）` }}
              </template>
            </el-table-column>
            <el-table-column prop="arrive_time" label="来访时间" />
            <el-table-column prop="created_at" label="申请时间" />
            <el-table-column prop="auditorUser.username" label="审核人" />

            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="small"
                  @click="handlerShow(scope.row, 'detail')"
                >
                  <i class="el-icon-view" style="font-size: 16px;" /> 查看
                </el-button>
                <el-button
                  v-if="editBtnVisible(scope.row)"
                  type="text"
                  size="small"
                  @click="handleEditRecord(scope.row)"
                >
                  编辑
                </el-button>
                <el-button
                  type="text"
                  size="small"
                  @click="hadleVisitorDet(scope.row)"
                >
                  <i class="el-icon-delete" style="font-size: 16px;" /> 删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

        </el-tab-pane>
        <EditRecord
          ref="record"
          :record="currentRecord"
          :type="recordType"
          @submitClick="submitClick"
        />
        <el-tab-pane label="访客审核列表" name="2">
          <el-table
            v-loading="loading"
            :data="data"
            style="width: 100%"
            border
          >
            <el-table-column prop="company_name" label="公司名称" />
            <el-table-column prop="visitor" label="来访人员（同行人员）">
              <template v-slot="{ row }">
                {{ `${row.visitor}（${row.fellow}人）` }}
              </template>
            </el-table-column>
            <el-table-column prop="phone" label="手机号" />
            <el-table-column prop="docking.username" label="对接人员（部门）">
              <template v-slot="{ row }">
                {{ `${row.docking.username}（${row.department.name}）` }}
              </template>
            </el-table-column>
            <el-table-column prop="arrive_time" label="来访时间" />
            <el-table-column prop="created_at" label="申请时间" />
            <el-table-column prop="created_at" label="状态">
              <template v-slot:header="{ column, $index }">

                <el-dropdown @command="handleCommand">
                  <span class="el-dropdown-link" style="color: rgb(144, 147, 153);">
                    状态<i class="el-icon-arrow-down el-icon--right" />
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="wait">等待审核</el-dropdown-item>
                    <el-dropdown-item command="success">审核成功</el-dropdown-item>
                    <el-dropdown-item command="fail">拒绝</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
              <template slot-scope="scope">
                <el-tag v-if="scope.row.agree == 'wait'" type="warning">等待审核</el-tag>
                <el-tag v-if="scope.row.agree == 'success'" type="success">审核成功</el-tag>
                <el-tag v-if="scope.row.agree == 'fail'" type="danger">拒绝</el-tag>
              </template>
            </el-table-column>

            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <!-- <el-button type="text" size="small" v-if="scope.row.type == '1'" :disabled="scope.row.type == '1' && scope.row.agree!=='wait'" @click="handlerShow(scope.row)">
                    <i class="el-icon-view"></i> 操作
                  </el-button> -->
                <el-button
                  type="text"
                  size="small"
                  :disabled="scope.row?.agree !== 'wait'"
                  @click="handlerShow(scope.row)"
                >
                  <svg-icon
                    :icon-class="
                      scope.row?.agree !== 'wait'
                    ? 'visitorExamine-disabled' : 'visitorExamine'"
                  />
                  审核
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <div class="pagination">
        <Pagination
          style="margin-top: 0; padding: 20px 0 0 0;"
          :total="meta.total"
          :limit="meta.per_page"
          @pagination="pagination"
        />
      </div>
    </div>

    <EditDialog
      v-model="currentEditRecord"
      :visible.sync="editDialogVisible"
      @confirm="handleEditDialogConfirm"
    />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import Pagination from '@/components/Pagination'
import EditRecord from './assembly/EditRecord.vue'
import { getVisitList, getNowVisitList, EditApproval, deleteVisitRecord } from '@/api/visitor'
import { getAllUser } from '@/api/v2/personnel'
import { getVisitorDataStatistics, editVisitor } from '@/api/v2/visitor'
import dayjs from 'dayjs'
import StatisticsCard from '@/components/StatisticsCard/StatisticsCard.vue'
import EditDialog from '@/views/visitor/components/EditDialog.vue'
export default {
  name: 'Documentation',
  components: { Pagination, EditRecord, StatisticsCard, EditDialog },
  directives: { // 注意：这个是写到data外面
    'el-select-loadmore': {
      bind(el, binding) {
        const SELECTWRAP_DOM = el.querySelector(
          '.el-select-dropdown .el-select-dropdown__wrap'
        )
        SELECTWRAP_DOM.addEventListener('scroll', function() {
          const condition =
            this.scrollHeight - this.scrollTop <= this.clientHeight
          if (condition) {
            binding.value()
          }
        })
      }
    }
  },
  data() {
    return {
      data: [],
      meta: {},
      pageData: {},
      form: {
        company_name: '',
        visitor: '',
        phone: '',
        time: '',
        docking_id: ''
      },
      first: {
        type: '',
        agree: '',
        exclude_status: 'wait'
      },
      loading: false,
      remoteMethodLoading: false,
      options: [],
      pageArr: {
        current: 1, // 当前页
        size: 50, // 每页显示条数
        last_page: ''
      },
      page: '',
      apply: {
        visitor: '',
        status: '',
        paginate: 10,
        page: 1
      },
      activeName: '1',
      invite: [],
      pageNumber: {},
      status: [{
        value: '',
        label: '全部'
      }, {
        value: 'success',
        label: '审核成功'
      }, {
        value: 'wait',
        label: '等待审核'
      }, {
        value: 'fail',
        label: '拒绝'
      }],
      value: '',
      isSearchUsername: false,
      statisticsData: null,
      statisticsDataLoading: false,
      currentRecord: null,
      recordType: 'examine',
      editDialogVisible: false,
      currentEditRecord: null
    }
  },
  computed: {
    ...mapGetters(['userId']),

    visitorDataStatistics() {
      return [
        {
          label: '今日未接待',
          value: this.statisticsData?.todayNotReceived,
          unit: '批',
          icon: 'todayNotReceived'
        },
        {
          label: '今日访客总量',
          value: this.statisticsData?.todayVisitory,
          unit: '批',
          icon: 'todayVisitory'
        },
        {
          label: '今日访客总人数',
          value: this.statisticsData?.todayVisitoryCount,
          unit: '人',
          icon: 'todayVisitoryCount'
        },
        {
          label: '未接待',
          value: this.statisticsData?.notReceived,
          unit: '批',
          icon: 'notReceived'
        },
        {
          label: '待审核',
          value: this.statisticsData?.waitCount,
          unit: '人',
          icon: 'visitorWait'
        }
      ]
    }
  },
  created() {
    this.getVisitLists()
    this.getUser()
    this.getNowVisitLists()
    this.getVisitorDataStatistics()
    console.log(this.userId.id, 66666666)
  },
  methods: {

    async getVisitorDataStatistics() {
      this.statisticsDataLoading = true
      try {
        const res = await getVisitorDataStatistics()
        this.statisticsData = res.data
      } catch (error) {
        throw new Error(error?.response?.data?.message || '访客数据统计获取失败')
      } finally {
        this.statisticsDataLoading = false
      }
    },

    remoteMethod(e) {
      console.log('e --------->', e)
      this.pageArr.current = 1
      this.getUser(e)
    },

    handlePersonUser(e) {
      if (this.isSearchUsername || this.pageArr.current !== 1) {
        this.pageArr.current = 1
        this.getUser()
        this.isSearchUsername = false
      }
    },

    // 懒加载
    loadmore() {
      if (this.pageArr.last_page <= this.pageArr.current) {
        return
      }
      this.pageArr.current++
      this.getUser()
    },
    async getNowVisitLists() {
      const res = await getNowVisitList(this.apply)
      this.invite = res.data
      this.pageNumber = res.meta
      console.log(res, 555555)
    },
    handleClick(type, e) {
      this.pageData = this.$options.data().pageData
      switch (this.activeName) {
        case '1':
          // this.first.type = ''
          this.first.agree = ''
          this.first.exclude_status = 'wait'
          // this.form.company_name = ''
          // this.form.visitor = ''
          // this.form.phone = ''
          // this.form.time = ''
          // this.form.docking_id = ''
          this.getVisitLists()
          break
        case '2':
          // this.first.type = ''
          this.first.agree = 'wait'
          this.first.exclude_status = ''
          // this.form.company_name = ''
          // this.form.visitor = ''
          // this.form.phone = ''
          // this.form.time = ''
          // this.form.docking_id = ''
          this.getVisitLists()
          break
      }
    },

    handleRest() {
      this.pageData = this.$options.data().pageData
      this.form = this.$options.data().form

      console.log('this.form --------->', this.form)

      if (this.activeName === '1') {
        this.first.agree = ''
        this.first.exclude_status = 'wait'
      } else {
        this.first.agree = 'wait'
        this.first.exclude_status = ''
      }

      this.getVisitLists()
    },

    select(e) {
      console.log(e, 789)
      this.apply.status = e
      this.getNowVisitLists()
    },
    async getVisitLists() {
      console.log(this.form)
      this.loading = true
      const params = Object.assign(this.pageData, this.form, this.first)
      const { data, meta } = await getVisitList(params)
      this.data = data
      console.log(this.data, 11111666666)
      this.meta = meta
      this.loading = false
    },
    async getUser(username) {
      this.remoteMethodLoading = true
      if (username) {
        this.isSearchUsername = true
      }
      const param = {
        // paginate: this.pageArr.size,
        // page: this.pageArr.current,
        job_status: JSON.stringify([1]),
        username: username,
        type: 2
      }
      getAllUser(param).then((res) => {
        console.log(res.data)
        // this.pageArr.last_page = res.meta.last_page
        // res.data.forEach(element => {
        //   this.options.push(element)
        // })
        this.options = res.data
        console.log(this.options)
      }).catch((err) => {

      }).finally(() => {
        this.remoteMethodLoading = false
      })
    },
    selectTime(arr) {
      console.log(arr, 'arr')
      if (arr) {
        this.form.start_at = dayjs(arr[0]).format('YYYY-MM-DD')
        this.form.end_at = dayjs(arr[1]).format('YYYY-MM-DD')
      } else {
        delete this.form.start_at
        delete this.form.end_at
        delete this.pageData?.start_at
        delete this.pageData?.end_at
      }
    },
    selectUser(arr) {
      if (!arr) {
        delete this.form.docking_id
      }
    },
    handlerShow(data, type = 'examine') {
      this.recordType = type
      this.$refs.record.visible = true
      this.$refs.record.ruleForm.id = data.id
      this.currentRecord = data
      console.log(data, 123321)
    },
    // 审批访客请求
    submitClick(data) {
      EditApproval(data).then(res => {
        this.$message({
          message: '审批成功',
          type: 'success'
        })
        this.getVisitLists()
        this.getNowVisitLists()
        this.$refs.record.visible = false
      }).catch(err => {
        this.$message({
          message: err,
          type: 'warning'
        })
      })
    },
    onSubmit() {
      this.pageData.page = 1
      this.getVisitLists()
    },
    pagination(page) {
      this.pageData.page = page.page
      this.pageData.paginate = page.limit
      this.getVisitLists()
    },
    pageChange(page) {
      this.apply.page = page.page
      this.apply.paginate = page.limit
      this.getNowVisitLists()
    },
    handleSearch() {
      this.apply.page = 1
      this.getNowVisitLists()
    },
    resetSearchInfo() {
      this.apply = this.$options.data().apply
      this.apply.visitor = this.$options.data().visitor
      this.getNowVisitLists()
    },
    async hadleVisitorDet(row) {
      try {
        this.$confirm('您确定要删除这条访客记录吗?', '提示').then(async() => {
          await deleteVisitRecord(row.id)
          this.$message.success('删除成功')
          await this.getVisitLists()
          await this.getVisitorDataStatistics()
        })
      } catch (error) {
        this.$message.error('删除失败')
        console.log(error, 'error')
      }
    },

    handleRowStyle(rowInfo) {
      const { row } = rowInfo
      if (dayjs().isAfter(row?.arrive_time)) {
        return {
          color: '#C0C4CC'
        }
      }
    },

    handleCommand(e) {
      console.log('e --------->', e)
      this.first.agree = e
      this.pageData = this.$options.data().pageData
      this.getVisitLists()
    },

    editBtnVisible(row) {
      if (dayjs().isAfter(row?.arrive_time)) return false
      return true
    },
    handleEditRecord(row) {
      console.log('row --------->', row)
      this.currentEditRecord = {
        id: row.id,
        company_name: row.company_name, // 来访单位
        visitor: row.visitor, // 来访人
        fellow: row.fellow, // 来访人数
        phone: row.phone, // 来访人电话
        arrive_time: row.arrive_time, // 来访时间
        reason: row.reason // 来访事由
      }

      this.editDialogVisible = true
    },

    handleEditDialogConfirm(e) {
      this.editVisitorFetch(e)
    },

    async editVisitorFetch(data) {
      try {
        const res = await editVisitor(data)
        this.$message.success('修改成功')
        this.editDialogVisible = false
        this.handleRest()
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '修改失败')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.visitor-list-documentation-container{
  padding: 0 20px 20px 20px;
  .work-title {
    font-size: 16px;
    font-weight: bold;
    margin: 20px 0;
  }

  .card {
    border-radius: 4px;
    margin-bottom: 20px !important;
  }

  .search {
    background-color: #fff;
    padding: 20px 20px 0 20px;
    ::v-deep(.el-form-item) {
      //margin-right: 20px;
      .el-form-item__label {
        font-weight: 400;
      }
    }
  }

  .list__content {
    padding: 10px 20px 20px 20px;
    background-color: #fff;
  }

  .data-statistics {
    margin-bottom: 20px;
  }

  .pagination {
    display: flex;
    justify-content: end;
  }
}

</style>
